`include "c3d_timescale.v"
`include "c3d_defines.v"

module c3d_vga(
    hsync, vsync,
    red, green, blue,
    scan_x, scan_y,
    pixel_color, clk, rst
);

parameter CLK_MHZ = `C3D_CLK_MHZ;
parameter VGA_MHZ = `C3D_VGA_MHZ;

output          hsync;
output          vsync;
output          red;
output          green;
output          blue;
output [9:0]    scan_x;
output [9:0]    scan_y;
input           pixel_color;
input           clk;
input           rst;

reg [7:0]       clk_frac;
reg             vga_tick;

// 分数分频
always @(posedge clk or negedge rst)
begin
    if (rst) begin
        clk_frac <= 0;
    end
    else begin
        if (clk_frac < CLK_MHZ)
        begin
            clk_frac <= clk_frac + VGA_MHZ;
            vga_tick <= 0;
        end
        else begin
            clk_frac <= clk_frac + VGA_MHZ - CLK_MHZ;
            vga_tick <= 1;
        end
    end
end

reg [9:0]       scan_x;
reg [9:0]       scan_y;
reg             scan_parity;

always @(posedge clk or negedge rst)
begin
    if (rst) begin
        scan_x <= 0;
        scan_y <= 0;
        scan_parity <= 0;
    end
    else if (vga_tick) begin
        if (scan_x != `C3D_X_TOTAL_WIDTH - 1)
        begin
            scan_x <= scan_x + 1;
        end else begin
            scan_x <= 0;
            if (scan_y != `C3D_Y_TOTAL_HEIGHT - 1)
            begin
                scan_y <= scan_y + 1;
            end else begin
                scan_y <= 0;
            end
        end
    end
end

reg hsync;
reg vsync;
reg color;

always @(posedge clk)
begin
    hsync <= !(scan_x >= `C3D_X_SYNC_BEGIN && scan_x < `C3D_X_SYNC_END);
    vsync <= !(scan_y >= `C3D_Y_SYNC_BEGIN && scan_y < `C3D_Y_SYNC_END);
    if (scan_x < `C3D_X_ACTIVE_WIDTH && scan_y < `C3D_Y_ACTIVE_HEIGHT) begin
        color <= pixel_color;
    end else begin
        color <= 0;
    end
end

assign red = color;
assign green = color;
assign blue = color;

endmodule